package com.czk.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/3/19 10:14
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 定义用户服务信息
     * 查询用户信息
     *
     * @return
     */
    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        // 基于内存的模拟
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        // 创建一个用户
        manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
        manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
        return manager;
    }

    /**
     * 密码编码机制
     * 定义密码比对规则
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
    /**
     * 安全拦截机制
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 拥有哪些权限才能访问
                .antMatchers("/r/r1").hasAnyAuthority("p1")
                .antMatchers("/r/r2").hasAnyAuthority("p2")
                // 这种请求需要全部认证
                .antMatchers("/r/**").authenticated()
                // 其他请求放行
                .anyRequest().permitAll()
                .and()
                // 允许表单登录
                .formLogin()
                // 认证成功的登录页面
                .successForwardUrl("/login-success");
    }
}
